package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.springboot.common.Result;
import org.example.springboot.entity.*;
import org.example.springboot.mapper.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MerchantService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MerchantService.class);

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private ReviewMapper reviewMapper;

    @Autowired
    private RefundMapper refundMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取商户仪表盘数据
     */
    public Result<?> getDashboardData(Long merchantId) {
        try {
            Map<String, Object> dashboardData = new HashMap<>();
            
            // 获取当前月份和上个月份
            LocalDate now = LocalDate.now();
            YearMonth currentMonth = YearMonth.from(now);
            YearMonth lastMonth = currentMonth.minusMonths(1);
            
            // 获取当前月订单数
            LocalDateTime currentMonthStart = currentMonth.atDay(1).atStartOfDay();
            LocalDateTime currentMonthEnd = currentMonth.atEndOfMonth().atTime(23, 59, 59);
            
            LOGGER.info("商户ID: {}, 当前月: {}, 上月: {}", merchantId, currentMonth, lastMonth);
            LOGGER.info("当前月日期范围: {} 到 {}", currentMonthStart, currentMonthEnd);
            
            // 查询商户所有商品
            List<Product> merchantProducts = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getMerchantId, merchantId));
            
            LOGGER.info("商户商品数量: {}", merchantProducts.size());
            
            if (merchantProducts.isEmpty()) {
                // 如果商户没有商品，返回空数据
                dashboardData.put("orderCount", 0);
                dashboardData.put("orderGrowth", 0);
                dashboardData.put("salesAmount", 0);
                dashboardData.put("salesGrowth", 0);
                dashboardData.put("productCount", 0);
                dashboardData.put("activeProductCount", 0);
                dashboardData.put("avgRating", 0);
                dashboardData.put("reviewCount", 0);
                return Result.success(dashboardData);
            }
            
            List<Long> productIds = merchantProducts.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());
            
            // 当前月订单数和销售额
            List<Order> currentMonthOrders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
                            .ge(Order::getCreatedAt, Timestamp.valueOf(currentMonthStart))
                            .le(Order::getCreatedAt, Timestamp.valueOf(currentMonthEnd))
                            .ne(Order::getStatus, 0) // 排除未支付订单
                            .ne(Order::getStatus, 4) // 排除已取消订单
                            .ne(Order::getStatus, 5) // 排除已退款订单
            );
            
            int currentMonthOrderCount = currentMonthOrders.size();
            BigDecimal currentMonthSales = currentMonthOrders.stream()
                    .map(Order::getTotalPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            LOGGER.info("当前月订单数: {}, 销售额: {}", currentMonthOrderCount, currentMonthSales);
            
            // 上个月订单数和销售额
            LocalDateTime lastMonthStart = lastMonth.atDay(1).atStartOfDay();
            LocalDateTime lastMonthEnd = lastMonth.atEndOfMonth().atTime(23, 59, 59);
            
            LOGGER.info("上月日期范围: {} 到 {}", lastMonthStart, lastMonthEnd);
            
            List<Order> lastMonthOrders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
                            .ge(Order::getCreatedAt, Timestamp.valueOf(lastMonthStart))
                            .le(Order::getCreatedAt, Timestamp.valueOf(lastMonthEnd))
                            .ne(Order::getStatus, 0) // 排除未支付订单
                            .ne(Order::getStatus, 4) // 排除已取消订单
                            .ne(Order::getStatus, 5) // 排除已退款订单
            );
            
            int lastMonthOrderCount = lastMonthOrders.size();
            BigDecimal lastMonthSales = lastMonthOrders.stream()
                    .map(Order::getTotalPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            LOGGER.info("上月订单数: {}, 销售额: {}", lastMonthOrderCount, lastMonthSales);
            
            // 计算增长率
            double orderGrowth = 0;
            if (lastMonthOrderCount > 0) {
                orderGrowth = ((double) (currentMonthOrderCount - lastMonthOrderCount) / lastMonthOrderCount) * 100;
            } else if (currentMonthOrderCount > 0) {
                // 如果上月没有订单但当前月有订单，则增长率为100%
                orderGrowth = 100.0;
            }
            
            double salesGrowth = 0;
            if (lastMonthSales.compareTo(BigDecimal.ZERO) > 0) {
                salesGrowth = (currentMonthSales.subtract(lastMonthSales)
                        .divide(lastMonthSales, 4, RoundingMode.HALF_UP)
                        .doubleValue()) * 100;
            } else if (currentMonthSales.compareTo(BigDecimal.ZERO) > 0) {
                // 如果上月没有销售额但当前月有销售额，则增长率为100%
                salesGrowth = 100.0;
            }
            
            LOGGER.info("订单增长率: {}, 销售额增长率: {}", orderGrowth, salesGrowth);
            
            // 商品总数和上架商品数
            int productCount = merchantProducts.size();
            int activeProductCount = (int) merchantProducts.stream()
                    .filter(p -> p.getStatus() == 1)
                    .count();
            
            // 评价数据
            List<Review> reviews = reviewMapper.selectList(
                    new LambdaQueryWrapper<Review>()
                            .in(Review::getProductId, productIds)
            );
            
            int reviewCount = reviews.size();
            double avgRating = 0;
            if (!reviews.isEmpty()) {
                avgRating = reviews.stream()
                        .mapToInt(Review::getRating)
                        .average()
                        .orElse(0);
            }
            
            LOGGER.info("商品总数: {}, 上架商品数: {}, 评价数: {}, 平均评分: {}", 
                    productCount, activeProductCount, reviewCount, avgRating);
            
            // 组装数据
            dashboardData.put("orderCount", currentMonthOrderCount);
            dashboardData.put("orderGrowth", Math.round(orderGrowth * 10) / 10.0); // 保留一位小数
            dashboardData.put("salesAmount", currentMonthSales.doubleValue());
            dashboardData.put("salesGrowth", Math.round(salesGrowth * 10) / 10.0); // 保留一位小数
            dashboardData.put("productCount", productCount);
            dashboardData.put("activeProductCount", activeProductCount);
            dashboardData.put("avgRating", Math.round(avgRating * 10) / 10.0); // 保留一位小数
            dashboardData.put("reviewCount", reviewCount);
            
            return Result.success(dashboardData);
        } catch (Exception e) {
            LOGGER.error("获取商户仪表盘数据失败: {}", e.getMessage(), e);
            return Result.error("-1", "获取商户仪表盘数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取商户销售趋势
     */
    public Result<?> getSalesTrend(Long merchantId, String period) {
        try {
            // 查询商户所有商品
            List<Product> merchantProducts = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getMerchantId, merchantId));
            
            if (merchantProducts.isEmpty()) {
                Map<String, Object> emptyData = new HashMap<>();
                emptyData.put("dates", Collections.emptyList());
                emptyData.put("sales", Collections.emptyList());
                return Result.success(emptyData);
            }
            
            List<Long> productIds = merchantProducts.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());
            
            // 根据周期确定开始和结束时间
            LocalDateTime startDate;
            LocalDateTime endDate = LocalDateTime.now().plusDays(1);
            DateTimeFormatter displayFormatter; // 用于显示
            DateTimeFormatter keyFormatter;     // 用于Map键匹配
            
            switch (period) {
                case "week":
                    startDate = LocalDateTime.now().minusDays(7);
                    displayFormatter = DateTimeFormatter.ofPattern("MM-dd");
                    keyFormatter = DateTimeFormatter.ofPattern("MM-dd");
                    break;
                case "year":
                    startDate = LocalDateTime.now().withMonth(1).withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
                    displayFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
                    keyFormatter = DateTimeFormatter.ofPattern("yyyy-MM");
                    break;
                case "month":
                default:
                    startDate = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0);
                    displayFormatter = DateTimeFormatter.ofPattern("MM-dd");
                    keyFormatter = DateTimeFormatter.ofPattern("MM-dd");
                    break;
            }
            LOGGER.info("startDate: {}, endDate: {}", startDate, endDate);
            // 查询订单 - 不排除任何状态，先获取所有订单
            List<Order> allOrders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
                            .ge(Order::getCreatedAt, Timestamp.valueOf(startDate))
                            .le(Order::getCreatedAt, Timestamp.valueOf(endDate))
            );
            
            // 过滤出有效订单（排除未支付、已取消、已退款）
            List<Order> orders = allOrders.stream()
                    .filter(order -> order.getStatus() != 0 && order.getStatus() != 4 && order.getStatus() != 5)
                    .toList();
            
            LOGGER.info("商户ID: {}, 周期: {}, 查询到订单总数: {}, 有效订单数: {}", 
                    merchantId, period, allOrders.size(), orders.size());
            
            // 按日期分组计算销售额
            Map<String, BigDecimal> salesByDate = new HashMap<>();
            
            // 初始化日期范围内的所有日期
            List<String> dateLabels = new ArrayList<>();
            if ("year".equals(period)) {
                // 按月统计，使用当前年份
                int currentYear = LocalDateTime.now().getYear();
                for (int i = 1; i <= 12; i++) {
                    LocalDateTime date = LocalDateTime.of(currentYear, i, 1, 0, 0);
                    String dateStr = date.format(displayFormatter);
                    dateLabels.add(dateStr);
                    salesByDate.put(dateStr, BigDecimal.ZERO);
                }
            } else {
                // 按日统计
                LocalDateTime current = startDate;
                while (!current.isAfter(endDate)) {
                    String dateStr = current.format(displayFormatter);
                    dateLabels.add(dateStr);
                    salesByDate.put(dateStr, BigDecimal.ZERO);
                    current = current.plusDays(1);
                }
            }
            
            // 统计每个日期的销售额
            for (Order order : orders) {
                LocalDateTime orderDate = order.getCreatedAt().toLocalDateTime();
                String dateKey = orderDate.format(keyFormatter);
                
                // 记录处理的订单信息，便于调试
                LOGGER.debug("处理订单: ID={}, 日期={}, 格式化后键={}, 金额={}", 
                        order.getId(), orderDate, dateKey, order.getTotalPrice());
                
                BigDecimal currentSales = salesByDate.getOrDefault(dateKey, BigDecimal.ZERO);
                salesByDate.put(dateKey, currentSales.add(order.getTotalPrice()));
            }
            
            // 组装结果
            List<Double> salesData = dateLabels.stream()
                    .map(date -> salesByDate.getOrDefault(date, BigDecimal.ZERO).doubleValue())
                    .collect(Collectors.toList());
            
            Map<String, Object> result = new HashMap<>();
            result.put("dates", dateLabels);
            result.put("sales", salesData);
            
            // 记录结果数据，便于调试
            LOGGER.info("销售趋势结果: 日期标签数量={}, 销售数据={}", 
                    dateLabels.size(), salesData);
            
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("获取商户销售趋势失败: {}", e.getMessage(), e);
            return Result.error("-1", "获取商户销售趋势失败: " + e.getMessage());
        }
    }

    /**
     * 获取商户订单状态分布
     */
    public Result<?> getOrderStatusDistribution(Long merchantId) {
        try {
            // 查询商户所有商品
            List<Product> merchantProducts = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getMerchantId, merchantId));
            
            if (merchantProducts.isEmpty()) {
                return Result.success(Collections.emptyList());
            }
            
            List<Long> productIds = merchantProducts.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());
            
            // 查询所有订单
            List<Order> orders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
            );
            
            // 订单状态映射
            Map<Integer, String> statusMap = new HashMap<>();
            statusMap.put(0, "待支付");
            statusMap.put(1, "已支付");
            statusMap.put(2, "已发货");
            statusMap.put(3, "已完成");
            statusMap.put(4, "已取消");
            statusMap.put(5, "已退款");
            
            // 统计各状态订单数量
            Map<Integer, Long> statusCount = orders.stream()
                    .collect(Collectors.groupingBy(Order::getStatus, Collectors.counting()));
            
            // 组装结果
            List<Map<String, Object>> result = new ArrayList<>();
            
            for (Map.Entry<Integer, String> entry : statusMap.entrySet()) {
                Integer status = entry.getKey();
                String statusName = entry.getValue();
                Long count = statusCount.getOrDefault(status, 0L);
                
                Map<String, Object> item = new HashMap<>();
                item.put("name", statusName);
                item.put("value", count);
                result.add(item);
            }
            
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("获取商户订单状态分布失败: {}", e.getMessage());
            return Result.error("-1", "获取商户订单状态分布失败: " + e.getMessage());
        }
    }

    /**
     * 获取商户热销商品
     */
    public Result<?> getTopProducts(Long merchantId, Integer limit) {
        try {
            // 查询商户所有上架商品
            List<Product> products = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getMerchantId, merchantId)
                            .eq(Product::getStatus, 1)
                            .orderByDesc(Product::getSalesCount)
                            .last("LIMIT " + limit)
            );
            
            // 组装结果
            List<Map<String, Object>> result = products.stream().map(product -> {
                Map<String, Object> item = new HashMap<>();
                item.put("id", product.getId());
                item.put("name", product.getName());
                item.put("salesCount", product.getSalesCount());
                item.put("imageUrl", product.getImageUrl());
                return item;
            }).collect(Collectors.toList());
            
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("获取商户热销商品失败: {}", e.getMessage());
            return Result.error("-1", "获取商户热销商品失败: " + e.getMessage());
        }
    }

    /**
     * 获取商户待处理事项
     */
    public Result<?> getPendingTasks(Long merchantId) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 查询商户所有商品
            List<Product> merchantProducts = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getMerchantId, merchantId));
            
            if (merchantProducts.isEmpty()) {
                result.put("pendingShipment", 0);
                result.put("pendingRefund", 0);
                result.put("lowStockProducts", 0);
                result.put("newReviews", 0);
                return Result.success(result);
            }
            
            List<Long> productIds = merchantProducts.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());
            
            // 待发货订单数
            int pendingShipment = orderMapper.selectCount(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
                            .eq(Order::getStatus, 1) // 已支付待发货
            ).intValue();
            
            // 待处理退款数
            List<Order> orders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
            );
            
            List<Long> orderIds = orders.stream()
                    .map(Order::getId)
                    .collect(Collectors.toList());
            
            int pendingRefund = 0;
            if (!orderIds.isEmpty()) {
                pendingRefund = refundMapper.selectCount(
                        new LambdaQueryWrapper<Refund>()
                                .in(Refund::getOrderId, orderIds)
                                .eq(Refund::getStatus, 0) // 申请中
                ).intValue();
            }
            
            // 库存不足商品数
            int lowStockProducts = (int) merchantProducts.stream()
                    .filter(p -> p.getStock() < 10 && p.getStatus() == 1) // 库存低于10且上架中
                    .count();
            
            // 最近一周新增评价数
            LocalDateTime oneWeekAgo = LocalDateTime.now().minusDays(7);
            
            int newReviews = 0;
            if (!productIds.isEmpty()) {
                newReviews = reviewMapper.selectCount(
                        new LambdaQueryWrapper<Review>()
                                .in(Review::getProductId, productIds)
                                .ge(Review::getCreatedAt, Timestamp.valueOf(oneWeekAgo))
                ).intValue();
            }
            
            // 组装结果
            result.put("pendingShipment", pendingShipment);
            result.put("pendingRefund", pendingRefund);
            result.put("lowStockProducts", lowStockProducts);
            result.put("newReviews", newReviews);
            
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("获取商户待处理事项失败: {}", e.getMessage());
            return Result.error("-1", "获取商户待处理事项失败: " + e.getMessage());
        }
    }

    /**
     * 获取商户统计指标
     */
    public Result<?> getMerchantMetrics(Long merchantId) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 查询商户所有商品
            List<Product> merchantProducts = productMapper.selectList(
                    new LambdaQueryWrapper<Product>()
                            .eq(Product::getMerchantId, merchantId));
            
            if (merchantProducts.isEmpty()) {
                result.put("refundRate", 0);
                result.put("avgOrderValue", 0);
                result.put("repurchaseRate", 0);
                result.put("ratingDistribution", Collections.emptyList());
                return Result.success(result);
            }
            
            List<Long> productIds = merchantProducts.stream()
                    .map(Product::getId)
                    .collect(Collectors.toList());
            
            // 查询所有订单
            List<Order> orders = orderMapper.selectList(
                    new LambdaQueryWrapper<Order>()
                            .in(Order::getProductId, productIds)
                            .ne(Order::getStatus, 0) // 排除未支付订单
            );
            
            if (orders.isEmpty()) {
                result.put("refundRate", 0);
                result.put("avgOrderValue", 0);
                result.put("repurchaseRate", 0);
                result.put("ratingDistribution", Collections.emptyList());
                return Result.success(result);
            }
            
            List<Long> orderIds = orders.stream()
                    .map(Order::getId)
                    .collect(Collectors.toList());
            
            // 1. 计算退货率
            int totalOrders = orders.size();
            int refundedOrders = 0;
            
            if (!orderIds.isEmpty()) {
                refundedOrders = refundMapper.selectCount(
                        new LambdaQueryWrapper<Refund>()
                                .in(Refund::getOrderId, orderIds)
                                .in(Refund::getStatus, Arrays.asList(1, 3, 4)) // 已同意、退款中、已退款
                ).intValue();
            }
            
            double refundRate = totalOrders > 0 ? ((double) refundedOrders / totalOrders) * 100 : 0;
            refundRate = Math.round(refundRate * 10) / 10.0; // 保留一位小数
            
            // 2. 计算客单价
            BigDecimal totalSales = orders.stream()
                    .map(Order::getTotalPrice)
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            
            double avgOrderValue = totalOrders > 0 ? 
                    totalSales.divide(new BigDecimal(totalOrders), 2, RoundingMode.HALF_UP).doubleValue() : 0;
            
            // 3. 计算复购率
            Set<Long> userIds = orders.stream()
                    .map(Order::getUserId)
                    .collect(Collectors.toSet());
            
            int totalCustomers = userIds.size();
            int repeatCustomers = 0;
            
            for (Long userId : userIds) {
                int orderCount = (int) orders.stream()
                        .filter(o -> o.getUserId().equals(userId))
                        .count();
                
                if (orderCount > 1) {
                    repeatCustomers++;
                }
            }
            
            double repurchaseRate = totalCustomers > 0 ? ((double) repeatCustomers / totalCustomers) * 100 : 0;
            repurchaseRate = Math.round(repurchaseRate * 10) / 10.0; // 保留一位小数
            
            // 4. 计算评分分布
            List<Review> reviews = reviewMapper.selectList(
                    new LambdaQueryWrapper<Review>()
                            .in(Review::getProductId, productIds)
            );
            
            Map<Integer, Long> ratingCounts = reviews.stream()
                    .collect(Collectors.groupingBy(Review::getRating, Collectors.counting()));
            
            List<Map<String, Object>> ratingDistribution = new ArrayList<>();
            for (int i = 1; i <= 5; i++) {
                Map<String, Object> ratingData = new HashMap<>();
                ratingData.put("rating", i);
                ratingData.put("count", ratingCounts.getOrDefault(i, 0L));
                ratingDistribution.add(ratingData);
            }
            
            // 组装结果
            result.put("refundRate", refundRate);
            result.put("avgOrderValue", avgOrderValue);
            result.put("repurchaseRate", repurchaseRate);
            result.put("ratingDistribution", ratingDistribution);
            
            return Result.success(result);
        } catch (Exception e) {
            LOGGER.error("获取商户统计指标失败: {}", e.getMessage());
            return Result.error("-1", "获取商户统计指标失败: " + e.getMessage());
        }
    }
} 